import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/nutrition_provider.dart';

class NutritionPage extends StatefulWidget {
  const NutritionPage({super.key});

  @override
  State<NutritionPage> createState() => _NutritionPageState();
}

class _NutritionPageState extends State<NutritionPage> {
  final TextEditingController _searchController = TextEditingController();

  Widget _buildNutritionCard(String title, dynamic value, String unit) {
    String displayValue;

    if (value == null) {
      displayValue = '未知';
    } else if (value is num) {
      displayValue = value == value.toInt()
          ? value.toInt().toString()
          : value.toStringAsFixed(2);
    } else {
      displayValue = value.toString();
    }

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
      margin: const EdgeInsets.symmetric(vertical: 6),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              '$displayValue $unit',
              style: const TextStyle(
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<NutritionProvider>(context);

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextField(
                controller: _searchController,
                decoration: const InputDecoration(
                  hintText: '输入食品名称 (例如: 油条)',
                  border: OutlineInputBorder(),
                ),
                onSubmitted: (_) =>
                    provider.fetchNutritionData(_searchController.text),
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: DropdownButtonFormField<int>(
                      value: provider.searchMode,
                      decoration: const InputDecoration(
                        labelText: '搜索模式',
                        border: OutlineInputBorder(),
                      ),
                      items: const [
                        DropdownMenuItem(value: 0, child: Text('营养成分')),
                        DropdownMenuItem(value: 1, child: Text('食品分类')),
                        DropdownMenuItem(value: 2, child: Text('营养正序')),
                        DropdownMenuItem(value: 3, child: Text('营养倒序')),
                      ],
                      onChanged: (value) {
                        if (value != null) {
                          provider.setSearchMode(value);
                        }
                      },
                    ),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () =>
                        provider.fetchNutritionData(_searchController.text),
                    child: const Text('查询'),
                  ),
                ],
              ),
            ],
          ),
        ),
        Expanded(
          child: provider.isLoading
              ? const Center(child: CircularProgressIndicator())
              : provider.nutritionData == null
                  ? Center(
                      child: provider.errorMessage.isNotEmpty
                          ? Text(provider.errorMessage)
                          : SingleChildScrollView(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.food_bank,
                                    size: 80,
                                    color: Colors.grey[400],
                                  ),
                                  const SizedBox(height: 16),
                                  Text(
                                    '输入食品名称查询营养成分',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                    )
                  : SingleChildScrollView(
                      padding: const EdgeInsets.all(16.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Card(
                            color: Theme.of(context)
                                .colorScheme
                                .primary
                                .withOpacity(0.1),
                            elevation: 3,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: Column(
                                children: [
                                  Text(
                                    provider.nutritionData?.name ?? '未知食品',
                                    style: const TextStyle(
                                      fontSize: 24,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  Text(
                                    '食品种类: ${provider.nutritionData?.type ?? '未知'}',
                                    style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          const SizedBox(height: 16),
                          const Text(
                            '基本营养素 (每100克)',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          _buildNutritionCard(
                              '热量', provider.nutritionData?.rl, '大卡'),
                          _buildNutritionCard(
                              '蛋白质', provider.nutritionData?.dbz, 'g'),
                          _buildNutritionCard(
                              '脂肪', provider.nutritionData?.zf, 'g'),
                          _buildNutritionCard(
                              '碳水化合物', provider.nutritionData?.shhf, 'g'),
                          _buildNutritionCard(
                              '膳食纤维', provider.nutritionData?.ssxw, 'g'),
                          const SizedBox(height: 16),
                          const Text(
                            '微量元素',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          _buildNutritionCard(
                              '钙', provider.nutritionData?.gai, 'mg'),
                          _buildNutritionCard(
                              '铁', provider.nutritionData?.tei, 'mg'),
                          _buildNutritionCard(
                              '锌', provider.nutritionData?.xin, 'mg'),
                          _buildNutritionCard(
                              '钠', provider.nutritionData?.la, 'mg'),
                          _buildNutritionCard(
                              '钾', provider.nutritionData?.jia, 'mg'),
                          _buildNutritionCard(
                              '磷', provider.nutritionData?.ling, 'mg'),
                          _buildNutritionCard(
                              '镁', provider.nutritionData?.mei, 'mg'),
                          _buildNutritionCard(
                              '硒', provider.nutritionData?.xi, 'μg'),
                          const SizedBox(height: 16),
                          const Text(
                            '维生素',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          _buildNutritionCard(
                              '维生素A', provider.nutritionData?.wssa, 'μg'),
                          _buildNutritionCard(
                              '维生素C', provider.nutritionData?.wsfc, 'mg'),
                          _buildNutritionCard(
                              '维生素E', provider.nutritionData?.wsse, 'mg'),
                          _buildNutritionCard(
                              '硫胺素', provider.nutritionData?.las, 'mg'),
                          _buildNutritionCard(
                              '核黄素', provider.nutritionData?.su, 'mg'),
                          _buildNutritionCard(
                              '烟酸', provider.nutritionData?.ys, 'mg'),
                          _buildNutritionCard(
                              '胆固醇', provider.nutritionData?.dgc, 'mg'),
                        ],
                      ),
                    ),
        ),
      ],
    );
  }
}
